#include "mytcpclient.h"
#include"QApplication"
#include"client.h"
#include"QMessageBox"
#include"QNetworkProxy"
client* clientWindow;
MyTcpClient::MyTcpClient(QObject* _clientWindow,std::string _ip,int _port) {
    ip=_ip;
    port=_port;;
    qDebug()<<"start client :"<<ip<<":"<<port;;
    clientWindow=static_cast<client*>(_clientWindow);
    clientWindow->rcvMsgBrower->append("rcv msg");
    clientSocket=new QTcpSocket();
    connect(clientSocket,&QTcpSocket::readyRead,this,&MyTcpClient::readData);


}

MyTcpClient::~MyTcpClient(){
    // 关闭连接
    clientSocket->disconnectFromHost();
    if (clientSocket->waitForDisconnected()) {
        qDebug() << "Disconnected from the server.";
    } else {
        qDebug() << "Error disconnecting from the server:" << clientSocket->errorString();
    }
}
void MyTcpClient::readData(){
    // 读取从服务器返回的数据
    QByteArray data = clientSocket->readAll();
    qDebug() << "Data from TcpServer:" << data;
    clientWindow->rcvMsgBrower->append(data);
    // 在这里可以进行自定义的异步处理逻辑
}
void MyTcpClient::connectServer(){
    QNetworkProxy::setApplicationProxy(QNetworkProxy::NoProxy);
    clientSocket->connectToHost(QString::fromStdString(ip),port);
    // 检查连接是否成功
    if (clientSocket->waitForConnected()) {
        qDebug() << "Connected to the server.";

        // 发送数据到服务器
        // clientSocket->write("Hello, server!");

        // 等待数据读取完成
        // if (clientSocket->waitForBytesWritten() && clientSocket->waitForReadyRead()) {
        //     // 读取从服务器返回的数据
        //     QByteArray data =clientSocket->readAll();
        //     qDebug() << "Data from server:" << data;
        // } else {
        //     qDebug() << "Error reading data from the server:" << clientSocket->errorString();
        // }


    } else {
        qDebug() << "Error connecting to the server:" << clientSocket->errorString();
    }
}

void MyTcpClient::disconnectServer(){
    // 关闭连接
    clientSocket->disconnectFromHost();
    if (clientSocket->waitForDisconnected()) {
        qDebug() << "Disconnected from the server.";
    } else {
        qDebug() << "Error disconnecting from the server:" << clientSocket->errorString();
    }
}
void MyTcpClient::sendMsgToServer(std::string message){

    qDebug()<<clientSocket->state();
    if (clientSocket->state()==QAbstractSocket::ConnectedState) {
        clientSocket->write(message.c_str());
    }else{
        QMessageBox::information(nullptr,QString::fromStdString("alert"),QString::fromStdString("客户端未连接"));
    }

}

